package com.qd.panda.service.park;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qd.common.panda.domain.entity.carpark.CarParkGasStationPriceDTO;
import com.qd.common.sys.constant.Constants;
import com.qd.common.sys.domain.entity.system.SystemSetDTO;
import com.qd.common.sys.domain.event.SystemSetEventDTO;
import com.qd.common.sys.event.SystemSetEvent;
import com.qd.panda.mapper.park.CarParkGasStationPriceMapper;
import com.qd.panda.model.CarParkGasStationPrice;
import com.qd.panda.service.stroke.BigDecimalUtil;
import com.qd.system.service.system.SystemSetService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * 油号价格
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class CarParkGasStationPriceService extends BaseService<CarParkGasStationPriceMapper, CarParkGasStationPrice> {

    private static final String PREFIX_ID = "panda_car_park_gas_station_price_id_{0}";
    private static final String PREFIX_LIST = "panda_car_park_gas_station_price_pId_{0}";
    private static final String PREFIX_UNIQUE_PANDA_CAR = "panda_car_park_gas_station_price_octaneNumber_{0}_pId_{1}";

    private final SystemSetService systemSetService;
    private final RedisTemplateUtil<CarParkGasStationPrice> redisTemplateUtil;
    private final ObjectMapper objectMapper;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public CarParkGasStationPriceDTO save(CarParkGasStationPriceDTO dto) {
        checkUnique(dto);
        final CarParkGasStationPrice model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public CarParkGasStationPriceDTO update(CarParkGasStationPriceDTO dto) {
        checkUnique(dto);
        final CarParkGasStationPrice historyModel = Optional.ofNullable(getById(dto.getId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final CarParkGasStationPrice model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            clearCache(model);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<CarParkGasStationPrice> mList) {
        try {
            if (!super.saveBatch(mList)) {
                throw new ApiException("批量添加失败");
            }
        } finally {
            clearCaches(mList);
        }
    }

    /**
     * 批量更新
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateBatchIds(List<CarParkGasStationPrice> mList) {
        final List<String> ids = mList.stream().map(CarParkGasStationPrice::getId).collect(toList());
        final List<CarParkGasStationPrice> historyModelList = checkIds(ids);
        try {
            if (!super.updateBatchById(mList)) {
                throw new ApiException("批量更新失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
            ids.clear();
        }
    }

    /**
     * 删除，单个
     *
     * @param id 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String id) {
        final CarParkGasStationPrice historyModel = Optional.ofNullable(getById(id)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(id)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        final List<CarParkGasStationPrice> historyModelList = checkIds(ids);
        try {
            if (!super.removeByIds(ids)) {
                throw new ApiException("批量删除失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(CarParkGasStationPriceDTO dto) {
        final QueryWrapper<CarParkGasStationPrice> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param id 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String id) {
        boolean exists = false;
        if (StringUtils.hasLength(id)) {
            final CarParkGasStationPrice model = getById(id);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param id 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public CarParkGasStationPrice getById(String id) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, id);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(id), CarParkGasStationPrice.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param id 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public CarParkGasStationPriceDTO getByIdDto(String id) {
        return Optional.ofNullable(getById(id)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public CarParkGasStationPrice getOne(CarParkGasStationPriceDTO dto) {
        final QueryWrapper<CarParkGasStationPrice> queryWrapper = createQueryWrapper(dto);
        CarParkGasStationPrice model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public CarParkGasStationPriceDTO getOneDto(CarParkGasStationPriceDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<CarParkGasStationPrice> getList(CarParkGasStationPriceDTO dto) {
        final QueryWrapper<CarParkGasStationPrice> queryWrapper = createQueryWrapper(dto);
        final List<CarParkGasStationPrice> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<CarParkGasStationPriceDTO> getListDto(CarParkGasStationPriceDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 根据唯一性索引获得数据
     * param octaneNumber
     * param pId
     *
     * @return 单条数据
     */
    @Transactional(readOnly = true)
    public CarParkGasStationPrice getUniqueByOctaneNumberAndPId(Integer octaneNumber, String pId) {
        final QueryWrapper<CarParkGasStationPrice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("octane_number", octaneNumber);
        queryWrapper.eq("p_id", pId);
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_CAR, octaneNumber, pId);
        final CarParkGasStationPrice model = redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getOne(queryWrapper, false), CarParkGasStationPrice.class);
        queryWrapper.clear();
        return model;
    }

    /**
     * 验证唯一性索引
     *
     * @param dto 页面对象
     */
    private void checkUnique(CarParkGasStationPriceDTO dto) {
        CarParkGasStationPrice model = getUniqueByOctaneNumberAndPId(dto.getOctaneNumber(), dto.getPId());
        if (null != model) {
            checkUnique(dto, model);
        }
    }

    /**
     * 验证唯一性索引
     *
     * @param dto   页面对象
     * @param model 根据约束字段查询出来的数据库对象
     */
    private void checkUnique(CarParkGasStationPriceDTO dto, CarParkGasStationPrice model) {
        if (!StringUtils.hasLength(dto.getId())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
        if (!dto.getId().equals(model.getId())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(CarParkGasStationPrice model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getId()));
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_LIST, model.getPId()));
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_CAR, model.getOctaneNumber(), model.getPId()));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<CarParkGasStationPrice> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getId())).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
        List<String> uniqueIds = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_CAR, model.getOctaneNumber(), model.getPId())).collect(toList());
        if (!uniqueIds.isEmpty()) {
            redisTemplateUtil.deleteByKey(uniqueIds);
            uniqueIds.clear();
        }
        Set<String> parkIds = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_LIST, model.getPId())).collect(Collectors.toSet());
        if (!parkIds.isEmpty()) {
            redisTemplateUtil.deleteByKey(parkIds);
            parkIds.clear();
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public CarParkGasStationPriceDTO modelToDto(CarParkGasStationPrice model) {
        if (null == model) {
            return null;
        }
        final CarParkGasStationPriceDTO dto = new CarParkGasStationPriceDTO();
        dto.setId(model.getId());
        dto.setOctaneNumber(model.getOctaneNumber());
        dto.setPrice(model.getPrice());
        dto.setCustomerDiscount(model.getCustomerDiscount());
        dto.setPId(model.getPId());
        dto.setCustomerPrice(model.getCustomerPrice());
        dto.setNozzleNumbers(model.getNozzleNumbers());
        dto.setStationPrice(model.getStationPrice());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public CarParkGasStationPrice dtoToModel(CarParkGasStationPriceDTO dto) {
        if (null == dto) {
            return null;
        }
        final CarParkGasStationPrice model = new CarParkGasStationPrice();
        model.setId(dto.getId());
        model.setOctaneNumber(dto.getOctaneNumber());
        model.setPrice(dto.getPrice());
        model.setCustomerDiscount(dto.getCustomerDiscount());
        model.setPId(dto.getPId());
        model.setCustomerPrice(dto.getCustomerPrice());
        model.setNozzleNumbers(dto.getNozzleNumbers());
        model.setStationPrice(dto.getStationPrice());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(CarParkGasStationPriceDTO dto) {
        dto.setCustomerPriceDisplay(Optional.ofNullable(dto.getCustomerPrice()).map(customerPrice -> BigDecimalUtil.buildDefaultScale(customerPrice).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setPriceDisplay(Optional.ofNullable(dto.getPrice()).map(price -> BigDecimalUtil.buildDefaultScale(price).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setStationPriceDisplay(Optional.ofNullable(dto.getStationPrice()).map(price -> BigDecimalUtil.buildDefaultScale(price).stripTrailingZeros().toPlainString()).orElse(""));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<CarParkGasStationPriceDTO> modelToDtoList(List<CarParkGasStationPrice> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<CarParkGasStationPrice> dtoToModelList(List<CarParkGasStationPriceDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<CarParkGasStationPrice> createQueryWrapper(CarParkGasStationPriceDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<CarParkGasStationPrice> createQueryWrapper(CarParkGasStationPriceDTO dto, String tableAlias) {
        final QueryWrapper<CarParkGasStationPrice> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getPId())) {
                queryWrapper.eq(tableAlias + "p_id", dto.getPId());
            }
        }
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<CarParkGasStationPrice> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<CarParkGasStationPrice> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(CarParkGasStationPrice::getId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteCarParkGasStationPriceByParkId(String parkId) {
        QueryWrapper<CarParkGasStationPrice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("p_id", parkId);
        final List<CarParkGasStationPrice> carParkGasStationPrices = super.getBaseMapper().selectList(queryWrapper);
        queryWrapper.clear();
        if(!carParkGasStationPrices.isEmpty()){
            final List<String> ids = carParkGasStationPrices.stream().map(CarParkGasStationPrice::getId).collect(toList());
            removeBatchIds(ids);
            ids.clear();
        }
    }

    @Transactional(readOnly = true)
    public List<CarParkGasStationPrice> getGasStationPriceListByParkId(String parkId) {
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_LIST, parkId);
        return redisTemplateUtil.getList(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> {
            QueryWrapper<CarParkGasStationPrice> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("p_id", parkId);
            queryWrapper.orderByAsc("customer_price");
            final List<CarParkGasStationPrice> carParkGasStationPrices = getBaseMapper().selectList(queryWrapper);
            queryWrapper.clear();
            return carParkGasStationPrices;
        }, CarParkGasStationPrice.class);
    }

    @Transactional(readOnly = true)
    public List<CarParkGasStationPriceDTO> getGasStationPriceDtoListByParkId(String parkId) {
        return Optional.ofNullable(getGasStationPriceListByParkId(parkId)).map(this::modelToDtoList).orElse(Collections.emptyList());
    }

    @SuppressWarnings("unchecked")
    @EventListener(classes = SystemSetEvent.class)
    @Transactional(rollbackFor = Exception.class)
    public void updateLoginUserStatus(SystemSetEvent event) {
        log.info("updateLoginUserStatus");
        final Object source = event.getSource();
        if (source instanceof SystemSetEventDTO) {
            final SystemSetEventDTO systemSetEventDTO = (SystemSetEventDTO) event.getSource();
            if (null != systemSetEventDTO) {
                build(systemSetEventDTO);
            }
        } else if (source instanceof List) {
            final List<SystemSetEventDTO> systemSetEventDTOList = (List<SystemSetEventDTO>) event.getSource();
            if (null != systemSetEventDTOList) {
                systemSetEventDTOList.forEach(this::build);
            }
        }
    }


    private void build(SystemSetEventDTO systemSetEventDTO) {
        //不处理删除的
        if (systemSetEventDTO.getOperator().equals(SystemSetEventDTO.DELETE)) {
            return;
        }
        final String code = systemSetEventDTO.getCode();
        if (StringUtils.hasLength(code)) {
            if (Constants.SYSTEM_OIL_PRICE.equals(code)) {
                updateCarParkGasStationPrice(code);
            }
        }
    }
    @Transactional(rollbackFor = Exception.class)
    public void updateCarParkGasStationPrice(String code) {
        final SystemSetDTO systemSet = systemSetService.getByIdDto(code);
        if (null == systemSet) {
            return;
        }
        final List<CarParkGasStationPrice> list = super.list();
        if (list.isEmpty()) {
            return;
        }

        final Map<String, List<CarParkGasStationPrice>> carParkGasStationPriceMap = list.stream().collect(Collectors.groupingBy(carParkGasStationPrice -> carParkGasStationPrice.getOctaneNumber() + ""));

        final List<CarParkGasStationPrice> updateList = new ArrayList<>();

        final JsonNode jsonNode = systemSet.getValue();
        Map<String, Double> map = objectMapper.convertValue(jsonNode, new TypeReference<>() {
        });
        for (String key : map.keySet()) {
            Double value = map.get(key);
            final List<CarParkGasStationPrice> l = carParkGasStationPriceMap.get(key);
            if (null == l) {
                continue;
            }
            final List<CarParkGasStationPrice> collect = l.stream().map(carParkGasStationPrice -> carParkGasStationPrice.setPrice(BigDecimal.valueOf(value))).collect(toList());
            updateList.addAll(collect);
        }
        if (!updateList.isEmpty()) {
            updateBatchIds(updateList);
        }
    }
}